package org.wevil.service.sys;

import org.wevil.props.ResProp;
import org.wevil.util.ExcelUtil;
import org.springframework.stereotype.Service;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLEncoder;
import java.util.List;
import java.util.Objects;

@Service
public class DownloadService {

    @Resource
    ResProp resProp;

    /**
     * 导出数据
     * @param list 要导出的数据
     * @param clazz 导出的数据类型
     * @param fileName 导出的文件名
     * */
    public void exportList(List<?> list, Class<?> clazz, String fileName){
        String filePath = resProp.getRootPath() + resProp.getTemplatePath();
        ExcelUtil.listExportExcel(filePath, list, clazz);
        download(filePath, fileName);
    }

    /**
     * 文件下载
     * @param fileName 指定下载的文件名。，如果不指定，则默认绝对路径的文件名。例如 xxx.xlsx
     * @param fileAbsolutePath 文件绝对路径，例如：C:/tmp/files/java-boot/template/xxx.xlsx
     * */
    public void download(String fileAbsolutePath, String fileName) {
        HttpServletResponse response = ((ServletRequestAttributes)
                Objects.requireNonNull(RequestContextHolder.getRequestAttributes())).getResponse();
        File file = new File(fileAbsolutePath);
        if(fileName==null || fileName.trim().length() ==0){
            fileName = file.getName();
        }
        if (file.exists()) {
            // 设置强制下载打开
            assert response != null;
            response.setContentType("APPLICATION/OCTET-STREAM");
            response.setCharacterEncoding("UTF-8");
            // 设置下面这行才能让js读取到Content-Disposition
            response.setHeader("Access-Control-Expose-Headers", "Content-Disposition");
            try {
                response.setHeader("Content-Disposition", "attachment;fileName=" + URLEncoder.encode(fileName,"utf-8"));
            } catch (UnsupportedEncodingException e) {
                throw new RuntimeException(e);
            }
            byte[] buffer = new byte[1024];
            FileInputStream fis = null;
            BufferedInputStream bis = null;
            try {
                fis = new FileInputStream(file);
                bis = new BufferedInputStream(fis);
                OutputStream outputStream = response.getOutputStream();
                int i = bis.read(buffer);
                while (i != -1) {
                    outputStream.write(buffer, 0, i);
                    i = bis.read(buffer);
                }
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                if (bis != null) {
                    try {
                        bis.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
                if (fis != null) {
                    try {
                        fis.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }
        }
    }
}
